import express from 'express'
import {checkLogin} from './middleWare/index.js'

import  tableModule from '../models/index.js';

const {
    usersModel,
    roleTypesModel
} = tableModule

const router = express.Router()
router.use(checkLogin)

// 绑定当前登录用户的角色信息
router.post("/bindRole", async (req,res)=>{
    const { roleCode } = req.body; 
    const { userId} = req;

    if (!roleCode) {
        return res.status(500).json({ 
            code:500,
            message:"参数缺失",
            data:null
        });
    }

    if(userId){
        let user = await usersModel.getUserByUniqueIdentifier({userId})
        if (!user) {
            return res.status(500).json({ 
                code:500,
                message:"用户不存在",
                data:null
            });
        }
        let tmpRoles = typeof user.roles == 'string' ? JSON.parse(user.roles) : user.roles  || []
        // 检查角色是否已绑定
        if (tmpRoles?.includes(roleCode)) {
            return res.status(500).json({ 
                code:500,
                message:"角色已绑定",
                data:null
            });
        }
        
        // 更新用户信息 _绑定角色并更新当前角色
        let bindres = await usersModel.updateUser(userId, {
            currentRoleCode: roleCode,  
            roles: [...tmpRoles, roleCode]
        })

        if(bindres){
            return res.json({
                code: 200,
                message: "角色绑定成功",
                data: true,
            });
        }else{
            return res.status(500).json({
                code: 500,
                message: "角色绑定失败",
                data: null,
            });
        }
    }else{
        res.json({
            code: 500,
            message: "未知异常",
            data:null,
        })  
    }
})


// 查询当前登录用户的信息
router.post("/searchUserInfo", async (req,res) => {
    const {userId} = req
    if(userId){
        let user = await usersModel.getUserByUniqueIdentifier({userId})
        if(user){
            let roleResult = await roleTypesModel.showDetailRoleInfo(user.roles)
            return res.json({
                code:200,
                message:"查询成功",
                data:{
                    "userName": user?.userName,
                    "phone": user?.phone,
                    "roles": roleResult || [],
                    "currentRoleCode":user?.currentRoleCode,
                    "lastLoginTime":user?.lastLoginTime,
                }
            })
        }else{
            return res.status(500).json({
                code:500,
                message:"用户不存在",
                data:null
            })
        }
    }else{
        return res.status(500).json({
            code:500,
            message:"未知异常",
            data:null
        })

    }
})


// 修改用户密码
router.post("/updatePassword", async (req,res)=>{
    const {userId} = req
    const {oldPassword,newPassword} = req.body

    if(oldPassword && newPassword){
        let user = await usersModel.getUserByUniqueIdentifier({userId})
        if(user?.password === oldPassword){
            if(newPassword.length<6){
                return res.status(500).json({
                    code:500,
                    message:"密码必须是6位以上",
                    data:null
                })
            }
            let updateRes = await usersModel.updateUser(userId, { password: newPassword })
            if(updateRes){
                return res.json({
                    code:200,
                    message:"修改成功",
                    data:true
                })
            }else{
                return res.status(500).json({
                    code:500,
                    message:"修改失败",
                    data:null
                })
            }
       }else{
        return res.status(500).json({
            code:500,
            message:"原密码输入错误",
            data:null
        })
       }
    }else{
        return res.status(500).json({
            code:500,
            message:"传参不完整",
            data:null
        })
    }
})


// 添加用户的第一个计划和期望
router.post('/addFirstPlan', async (req,res)=>{
    const {userId} = req
    const {currentPlan, featureWish} = req.body
    if(currentPlan && featureWish){
        let updateRes = await usersModel.updateUser(userId, {
            firstPlan: currentPlan,
            firstFeatureWish: featureWish   
        })
        if(updateRes){
             return res.json({
                    code:200,
                    message:'添加成功',
                    data:true
                })
        }else{
            return res.status(500).json({
                code:500,
                message:"添加失败",
                data:null
            })
        }
    }else{
        return res.status(500).json({
            code:500,
            message:"传参不完整",
            data:null
        })
    }
})

export default router
